﻿using Emgu.CV;
using Emgu.CV.Structure;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bear.Library.Util
{
    public class CvHelper
    {

        public static bool TemplateMatching(Bitmap source, Image<Gray, byte> template, double score)
        {
            using (Image<Gray, Byte> sourceImage = new Image<Gray, byte>(source))
            {

                List<Point> returnValue = CvHelper.TemplateMatching(sourceImage, template, score);

                return returnValue.Count > 0;                
            }
        }



        public static List<Point> TemplateMatching(Bitmap source, Bitmap template, double score)
        {
            using (Image<Gray, Byte> sourceImage = new Image<Gray, byte>(source))
            {
                using (Image<Gray, Byte> templateImage = new Image<Gray, byte>(template))
                {
                    List<Point> returnValue = CvHelper.TemplateMatching(sourceImage, templateImage, score);
                    return returnValue;
                }
            }
        }

        public static List<Point> TemplateMatching(Image<Gray, byte> source, Image<Gray, byte> template, double score)
        {
            List<Point> result = new List<Point>();
            Image<Gray, float> resultImage = source.MatchTemplate(template, Emgu.CV.CvEnum.TM_TYPE.CV_TM_CCOEFF_NORMED);

            float[, ,] matches = resultImage.Data;

            for (int x = 0; x < matches.GetLength(1); x++)
            {
                for (int y = 0; y < matches.GetLength(0); y++)
                {
                    double matchScore = matches[y, x, 0];

                    if (matchScore > score)
                    {
                        result.Add(new Point(x, y));
                    }
                }
            }

            return result;
        }

        public static List<Point> TemplateMatching(Image<Bgr, byte> source, Image<Bgr, byte> template, double score)
        {
            List<Point> result = new List<Point>();
            Image<Gray, float> resultImage = source.MatchTemplate(template, Emgu.CV.CvEnum.TM_TYPE.CV_TM_CCOEFF_NORMED);

            float[, ,] matches = resultImage.Data;

            for (int x = 0; x < matches.GetLength(1); x++)
            {
                for (int y = 0; y < matches.GetLength(0); y++)
                {
                    double matchScore = matches[y, x, 0];

                    if (matchScore > score)
                    {
                        result.Add(new Point(x, y));
                    }
                }
            }

            return result;
        }


    }

}
